import CryptoJs from 'crypto-js';

const aesUtil = {
    //获取key，
    genKey: function (length = 16) {
        let random = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        let str = "";
        for (let i = 0; i < length; i++) {
            str = str + random.charAt(Math.random() * random.length)
        }
        return str;
    },

    //加密
    encrypt: function (plaintext, key) {
        if (plaintext instanceof Object) {
            //JSON.stringify
            plaintext = JSON.stringify(plaintext)
        }
        let encrypted = CryptoJs.AES.encrypt(CryptoJs.enc.Utf8.parse(plaintext), CryptoJs.enc.Utf8.parse(key), {
            mode: CryptoJs.mode.ECB,
            padding: CryptoJs.pad.Pkcs7
        });
        return encrypted.toString();
    },

    //解密
    decrypt: function (ciphertext, key) {
        let decrypt = CryptoJs.AES.decrypt(ciphertext, CryptoJs.enc.Utf8.parse(key), {
            mode: CryptoJs.mode.ECB,
            padding: CryptoJs.pad.Pkcs7
        });
        let decString = CryptoJs.enc.Utf8.stringify(decrypt).toString();
        if (decString.charAt(0) === "{" || decString.charAt(0) === "[") {
            //JSON.parse
            decString = JSON.parse(decString);
        }
        return decString;
    }
}

export default aesUtil
